﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;

namespace WebChatServer.Models
{
    public class MemberRepository : IMemberRepository
    {
        AccountEntities _entities = new AccountEntities();
        GroupRepository _groupRepository = new GroupRepository();

        public bool isExist(string chatMemberId)
        {
            var lstMem = from mem in _entities.Members
                         where mem.Id == chatMemberId
                          select mem;

            if (lstMem != null && lstMem.Count() > 0)
            {
                return true;
            }

            return false;
        }

        public Member Check(string chatMemberId)
        {
            var lstMem = from mem in _entities.Members
                         where mem.Id == chatMemberId
                         select mem;

            if (lstMem != null && lstMem.Count() > 0)
            {
                return lstMem.ToArray()[0];
            }

            return null;
        }

        public ChatMember Add(ChatMember chatmember)
        {
            if (isExist(chatmember.Id))
                return null;

            //add member
            Member member = new Member();
            member.Id = chatmember.Id;
            member.Password = chatmember.Password;
            member.Name = chatmember.Name;
            member.Image = "App_Data/Images/" + member.Id + ".jpg";
            member.IsExist = true;

            //add group WebChat mặc định
            Group wcgroup = new Group();
            wcgroup.IDMember = chatmember.Id;
            wcgroup.IDGroup = chatmember.Id + "_" + "WebChat";
            wcgroup.Name = "WebChat";
            wcgroup.IsExist = true;

            //add group Yahoo mặc định
            Group yhgroup = new Group();
            yhgroup.IDMember = chatmember.Id;
            yhgroup.IDGroup = chatmember.Id + "_" + "Yahoo";
            yhgroup.Name = "Yahoo";
            yhgroup.IsExist = true;

            _entities.Members.AddObject(member);
            _entities.SaveChanges();

            _entities.Groups.AddObject(wcgroup);
            _entities.Groups.AddObject(yhgroup);
            _entities.SaveChanges();

            

            return chatmember;
        }

        public MemberRepository()
        {
            
        }

        public IEnumerable<ChatMember> GetAll()
        {

            return null;
        }
        
        public Member[] getFriendsInGroup(string groupId)
        {
            var lstMem = from mem in _entities.FriendShips
                         where mem.IDGroup == groupId
                         select mem;

            if (lstMem != null && lstMem.Count() > 0)
            {
                FriendShip[] friendShip = lstMem.ToArray();
                Member[] friends = new Member[friendShip.Count()];
                for (int i = 0; i < friendShip.Count(); i++)
                {
                    string idfriend = friendShip[i].IDFriend;
                    var lstMem1 = from mem in _entities.Members
                                  where mem.Id == idfriend
                                  select mem;
                    if (lstMem1 != null && lstMem1.Count() > 0)
                    {
                        friends[i] = lstMem1.ToArray()[0];
                    }
                    else
                    {
                        friends[i] = null;
                    }
                }

                return friends;
            }

            return null;
        }

        public ChatMember Get(string id)
        {
            if (isExist(id) == false)
                return null;

            Member member = Check(id);
            Group[] groups = _groupRepository.Check(id);

            FriendGroup[] gGroups = new FriendGroup[groups.Count()];
            for (int i = 0; i < groups.Count(); i++)
            {
                Member[] friendsInGroup = getFriendsInGroup(groups[i].IDGroup);
                Friend[] friends = null;
                if (friendsInGroup != null)
                {

                    friends = new Friend[friendsInGroup.Count()];

                    for (int j = 0; j < friendsInGroup.Count(); j++)
                    {
                        MyImage image = new MyImage()
                                            {Name = friendsInGroup[j].Name, Array = GetImage(friendsInGroup[j].Image)};
                        friends[j] = new Friend()
                                         {
                                             GroupName = groups[i].Name,
                                             Id = friendsInGroup[j].Id,
                                             Image = image,
                                             MemberId = groups[i].IDMember,
                                             Name = friendsInGroup[j].Name,
                                             State = true
                                         };
                    }
                }
                gGroups[i] = new FriendGroup(){GroupId = groups[i].IDGroup, Name = groups[i].Name, UserName = groups[i].IDMember, Friends = friends};
                
            }

            return new ChatMember()
                       {
                           Id = id,
                           Password = member.Password,
                           Name = member.Name,
                           Groups = gGroups,
                           Image = new MyImage()
                                       {
                                           Name = member.Name, Array = GetImage(member.Image)
                                       }
                       };
        }

        

        public bool Remove(string memberId)
        {
            var delsta = from mem in _entities.Members
                         where mem.Id == memberId
                         select mem;

            if (delsta != null)
            {
                _entities.Members.DeleteObject(delsta.First());
                _entities.SaveChanges();
                return true;
            }
            return false;
        }

        public bool UpdateInfo(Update member)
        {
            Member mem = _entities.Members.Single(u => u.Id == member.Id);
            mem.Name = member.Name;
            mem.Password = member.Password;
            _entities.SaveChanges();
            return true;
        }


        public Byte[] GetImage(string file)
        {
            if (file != "null")
            {
                string imageName = HttpContext.Current.Server.MapPath("~/" + file);
                if (imageName != null)
                {
                    byte[] total = new byte[0];
                    Stream fileStream = File.Open(imageName, FileMode.Open, FileAccess.Read);
                    if (fileStream != null)
                    {
                        byte[] array = new byte[0];
                        byte[] buffer = new byte[32];
                        int read = 0;
                        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            array = new byte[total.Length + read];
                            total.CopyTo(array, 0);
                            Array.Copy(buffer, 0, array, total.Length, read);
                            total = array;
                        }
                        fileStream.Close();
                        return total;
                    }
                }
            }
            return new byte[0];
        }

        public bool IsMember(Login login)
        {
            Member mem = _entities.Members.Single(u => u.Id == login.UserName);
            if (mem.Password == login.Password)
                return true;
            return false;
        }

        public bool UserNameIsExist(Register register)
        {
            var lstMem = from mem in _entities.Members
                         where mem.Id == register.UserName
                         select mem;

            if (lstMem != null && lstMem.Count() > 0)
            {
                return false;
            }

            return true;
        }

        public Register AddMember(Register chatmember)
        {
            if (isExist(chatmember.UserName))
                return null;

            //add member
            Member member = new Member();
            member.Id = chatmember.UserName;
            member.Password = chatmember.Password;
            member.Name = chatmember.FullName;
            member.Image = "App_Data/Images/" + member.Id + ".jpg";
            member.IsExist = true;

            //add group WebChat mặc định
            Group wcgroup = new Group();
            wcgroup.IDMember = chatmember.UserName;
            wcgroup.IDGroup = chatmember.UserName + "_" + "WebChat";
            wcgroup.Name = "WebChat";
            wcgroup.IsExist = true;

            //add group Yahoo mặc định
            Group yhgroup = new Group();
            yhgroup.IDMember = chatmember.UserName;
            yhgroup.IDGroup = chatmember.UserName + "_" + "Yahoo";
            yhgroup.Name = "Yahoo";
            yhgroup.IsExist = true;

            _entities.Members.AddObject(member);
            _entities.SaveChanges();

            _entities.Groups.AddObject(wcgroup);
            _entities.Groups.AddObject(yhgroup);
            _entities.SaveChanges();

            string imageFile = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data/Images/no_avatar.jpg"));
            string file = Path.GetFullPath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data/Images/"));
            Image image = Image.FromFile(imageFile);
            image.Save(file + chatmember.UserName + ".jpg");

            return chatmember;
        }
    }
}